package com.zhyz.bookstore.servlet;

import com.alibaba.druid.support.json.JSONUtils;
import com.zhyz.bookstore.entity.*;
import com.zhyz.bookstore.service.OrdersService;
import com.zhyz.bookstore.service.impl.OrdersServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单管理servlet
 */
@WebServlet(name = "OrderServlet ", value = "/order/orderServlet")
public class OrderServlet extends HttpServlet {

    private OrdersService ordersService = new OrdersServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String op = req.getParameter("op");// 得到传过来的请求
        // 生成订单
        if ("genOrder".equals(op)) {
            newOrder(req, resp);
        }
        // 查看订单
        if ("findOrders".equals(op)) {
            findOrders(req, resp);
        }
        // 管理员查看订单
        if ("findAllOrders".equals(op)) {
            findAllOrders(req, resp);
        }
        // 发货
        if ("fahuo".equals(op)) {
            updateNewOrder(req, resp);
        }
        if("deleteOrder".equals(op)){
            deleteOrder(req,resp);
        }
        if("orderlist".equals(op)){
            orderList(req,resp);
        }
        if ("buy".equals(op)) {
            updateNewOrder(req, resp);
        }


    }

    private void updateNewOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String orderNum = req.getParameter("ordernum");
        String opp = req.getParameter("opp");
        ordersService.deliverOrder(orderNum,Integer.parseInt(opp));
        List<Orders> orders = ordersService.queryOrderByAdmin();
        HttpSession session = req.getSession();
        session.setAttribute("orders", orders);
        System.out.println(orders);
        if("1".equals(opp)){
            req.setAttribute("message", "付款成功！");
            req.getRequestDispatcher("/message.jsp").forward(req, resp);
        }else {
            resp.sendRedirect(req.getContextPath() + "/admin/managerOrder.jsp");
        }
    }

    private void orderList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<OrderItems> orderItemsList = ordersService.queryOrderItemsByOrderId(req.getParameter("ordernum"));

        resp.getWriter().print(orderItemsList);
    }


    //生成订单
    //获取用户购物车数据
    //生成订单号
    //生成订单信息
    //生成对应的订单项
    //清空已选购物车的信息

    private void newOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // 取出购物车信息
        // 取出购物项信息
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        User user = (User) session.getAttribute("user");
        if (cart == null) {
            resp.getWriter().write("会话已经结束！！");
            return;
        }
        Orders order = new Orders();
        order.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        String ordernum = getOrdersNum();
        order.setOrdernum(ordernum);
        order.setQuantity(cart.getTotalQuantity());
        order.setMoney(cart.getTotalMoney());
        order.setUser(user);
        // 订单项
        List<OrderItems> oItems = new ArrayList<OrderItems>();
        for (Map.Entry<String, CartItem> me : cart.getItmes().entrySet()) {
            CartItem cItem = me.getValue();
            OrderItems oItem = new OrderItems();
            oItem.setId(getOrdersNum());
            oItem.setBookid(cItem.getBook().getBookId());
            oItem.setPrice(cItem.getMoney());
            oItem.setQuantity(cItem.getQuantity());
            oItem.setOrdernum(ordernum);
            oItems.add(oItem);
        }
        // 建立订单项和订单的关系
        order.setItems(oItems);

        req.setAttribute("order", order);
        ordersService.save(order);
        session.removeAttribute("cart");
        req.getRequestDispatcher("/order.jsp").forward(req, resp);
    }



    //用户查询订单
    //根据用户ID查询订单
    private void findOrders(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        /**
         * 获取当前用户
         */
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        List<Orders> orders = ordersService.queryOrdersByUser(user);
//        JSONUtils.toJSONString(orders);
        session.setAttribute("orders", orders);
        req.getRequestDispatcher("/user/userOrder.jsp").forward(req, resp);
    }
    //用户删除订单
    //根据用户选择的订单ID删除订单以及对应的订单项
    //只能删除已完成的订单
    private void deleteOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String orderNum = req.getParameter("ordernum");
        boolean b = ordersService.deleteOrderByOrderId(orderNum);
        resp.getWriter().write(""+b);
    }

    //管理员查询订单
    //管理员查询所有订单

    private void findAllOrders(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        List<Orders> orders = ordersService.queryOrderByAdmin();
        HttpSession session = req.getSession();
        session.setAttribute("orders", orders);
        req.getRequestDispatcher("/admin/managerOrder.jsp").forward(req, resp);
    }


    //管理员操作订单
    //发货
    //只能对未发货的订单进行发货操作
    //删除
    private void updateOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String orderNum = req.getParameter("ordernum");
        ordersService.deliverOrder(orderNum,1);
        List<Orders> orders = ordersService.queryOrderByAdmin();
        HttpSession session = req.getSession();
        session.setAttribute("orders", orders);
        System.out.println(orders);
        resp.sendRedirect(req.getContextPath() + "/admin/managerOrder.jsp");
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }


    // 生成订单号
    private String getOrdersNum() {
        Date now = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String s1 = df.format(now);
        return s1 + System.nanoTime();
    }





}
